// packageA/pages/factoryTypeAdd/factoryTypeAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //信息
    editInfo:{},
    //设备类型选择框
    showType:false,
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //显示上传组件
    showUpload:true,
    //上传的图片
    imgUrls:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })  
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let user=app.globalData.userInfo;  

    //设备分类必填
    // if(!editInfo.category){
    //     Toast.fail('请选择设备分类');
    //     return;
    //   }

    //型号必填
    let typeCode=obj.typeCode.trim();
    if(!this.formNotEmpty(typeCode,'typeCodeMessage','请输入设备型号')){
      return;
    }

    //清洁数据必填
    let cleanArea=obj.cleanArea.trim();
    if(!this.formNotEmpty(cleanArea,'cleanAreaMessage','请输入清洁数据')){
      return;
    }

    //清洁数据是数字
    if(cleanArea!='' && cleanArea!=null){
        if(!(/^\d+(\.\d+)?$/.test(cleanArea))){
            this.setData({
                cleanAreaMessage: '清洁数据为数字',
                disabled: true
            });
            return;
        }
    }    

    //权限
    let authArr=[user.depart,user.departObj[0].companyId];
    let authSet=new Set(authArr);
    authArr=Array.from(authSet);

    let param={
      className:'equipmentBase',
      data:{
        requestToken: td.code,
        factoryId: user.depart,
        category: editInfo.category,
        typeCode: typeCode,
        cleanArea: cleanArea,
        iconUrl: td.imgUrls[0],
        createUser: user.id,
        dataAuthority: {
          depart: authArr
        }
      }
    }
    
    // console.log(param.data);
    // return;

    //避免表单重复提交
    Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '数据提交中...'
      });  

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
            this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    }) 
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  }, 

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  }, 
  
  //显示上传图片组件
  onShowUpload(){
    this.setData({
		showUpload: true
	})
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;

    if(imgUrls.length){
      this.setData({
        imgUrls: imgUrls
      })
    }
  },  

  //显示设备类型选择框
  onShowType(){
    this.setData({
		showType: true
    })
    //查询一级
    this.findEquipmentCategory();
  },

  //隐藏设备类型选择框
  onCloseType(){
    this.setData({
		showType: false
    })
  },

  //选择设备类型
  onChangeType(event) {
    const { picker, value, index } = event.detail;
    let arr=picker.getValues();
    this.findChildren(arr[0].id);
  },

  //确认设备类型
  onConfirmType(e){
    let arr=e.detail.value;
    let obj={};   

    if(arr[arr.length-1]){
        obj=arr[arr.length-1];
    }else{
        obj=arr[0]; 
    }

    let category='editInfo.category';
    this.setData({
        [category]:{
            id:obj.id,
            name:obj.text
        }   
    })
    
    this.onCloseType();
  },

  //查询设备一级分类
  findEquipmentCategory(){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: 1,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        this.setData({
          typeOne: cateArr
        })
        //查询子分类
        this.findChildren(result[0].id);
      }
    }).catch((error) => {
    })
  },

  //查询子分类
  findChildren(fid){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: fid,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      let typeOne=this.data.typeOne;
      //处理分类数据格式
      let typeList=[{
        values: typeOne,
        className: 'column1'
      }]

      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        typeList.push({
          values: cateArr,
          className: 'column2'
        });
      }else{
        typeList.push({
          values: [],
          className: 'column2'
        });
      }

      this.setData({
        typeList: typeList
      })
    }).catch((error) => {
    })
  },

  //返回操作
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.getFactoryType(); 
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
